const Koa = require('koa');
const cors = require('koa2-cors');
const Router = require('koa-router');
const glob = require("glob");
const { resolve } = require('path');
const fs = require('fs');
 
const app = new Koa();
app.use(cors());
const router = new Router({prefix: '/api/app'});

let routerMap = {};  // 存放路由映射
function regist_router (method,apiPath,data){
    // console.log(method,apiPath,data)
    if(method == "GET"){
        router.get(apiPath, (ctx, next) => {
            try {
                
                ctx.set("Content-Type", "application/json")
                ctx.body = JSON.parse(data)
            }catch(err) {
                ctx.throw(err);
            }
          });
    }else if(method == "POST"){
        router.post(apiPath, (ctx, next) => {
            try {
                ctx.set("Content-Type", "application/json")
                ctx.body = JSON.parse(data)
            }catch(err) {
                ctx.throw('服务器错误', 500);
            }
          });
    }
    
}
// 注册路由
glob.sync(resolve('./postman_collection', "**/*.json")).forEach((item, i) => {
    // let apiJsonPath = item && item.split('/api')[1];
    // let apiPath = apiJsonPath.replace('.json', '');
    


      // 记录路由
    // routerMap[apiJsonPath] = apiPath;

    let data = JSON.parse(fs.readFileSync(item));
    getRequest(data);
    console.log(routerMap)
    routerMap=JSON.stringify(routerMap);
    // routerMap = fs.readFileSync(item).toString();
});
function getRequest (data){
    data.item.forEach(item =>{
        if(item.request){
            // item.request.url.raw = item.request.url.raw.replace('{{host}}', '')
            let path = "/" + item.request.url.path.join("/");
            routerMap[`${item.request.method}-${path}`]=item.name;

            if(item.response[0]){
                
                regist_router(item.request.method,path,item.response[0].body)
            }
            
        }
        if(item.item){
            getRequest(item)
        }  
    })
}
fs.writeFile('./routerMap.json', routerMap, err => {
    if(!err) {
        console.log('路由地图生成成功！')
    }
});

app
  .use(router.routes())
  .use(router.allowedMethods());
app.listen(3000);